import re

from django.db.models import Q
from rest_framework.views import APIView
from rest_framework.viewsets import ViewSet

from utils.response import *
from utils.code_enum import *
from utils.params_filter import allow_edit, get_page
from .serializers import SystemUserSerializer
from .models import SystemUser
from apps.user.lib.auth_tool import set_jwt


# 用户登录
class LoginView(APIView):
	authentication_classes = []
	permission_classes = []

	def post(self, request):
		username = request.data.get('username')
		password = request.data.get('password')
		if not username:
			return ErrorResponse(msg="请输入用户名")
		if not password:
			return ErrorResponse(msg="请输入密码")
		user = SystemUser.objects.filter(username=username).filter(deleted=False).first()

		if user is None or not user.check_password(password):
			return ErrorResponse(msg="用户或密码错误")
		elif not user.status and not user.deleted:
			return ErrorResponse(msg="用户已停用")
		elif user.check_password(password):
			return SuccessResponse(msg="登录成功", data={"token": set_jwt(user.id)})


class SystemUserInfoViewSet(ViewSet):

	# 注册用户
	def register_user(self, request):
		user_name = request.data.get('username')
		if not user_name:
			return ErrorResponse(msg='请求参数错误')
		user = SystemUser.objects.filter(deleted=False).filter(username=user_name).first()
		if user:
			return ErrorResponse(msg='用户已注册')
		mobile = request.data.get('mobile')
		email = request.data.get('email')
		password = request.data.get('password')
		role = request.data.get('role')
		if not mobile:
			return ErrorResponse(msg='mobile是必传字段')
		if not email:
			return ErrorResponse(msg='email是必传字段')
		if not password:
			return ErrorResponse(msg='password是必传字段')

		# 验证用户名
		if user_name and not re.match(r'^[a-zA-Z0-9_]{3,20}$', user_name):
			return ErrorResponse(msg='用户名只允许输入3至20位字母、数字、_')

		# 验证手机号格式
		if mobile and not re.match(r'^1[356789]\d{9}$', mobile):
			return ErrorResponse(msg="输入的手机号格式不正确")

		# 验证邮箱格式
		if email and not re.match(r'^[0-9a-zA-Z_.-]+@[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*\.[0-9a-zA-Z-]{2,6}$', email):
			return ErrorResponse(msg="输入的邮箱地址不正确")

		if not role:
			return ErrorResponse(msg='请选择用户权限')

		userinfo = {
			'username': user_name,
			'mobile': mobile,
			'email': email,
			'password': password,
			'role': role
		}

		SystemUser.objects.create_user(**userinfo)
		return SuccessResponse(code=ResponseCode.CREATE_SUCCESS, msg="注册成功")

	# 用户列表
	def list(self, request):
		data = get_page(request, SystemUser, SystemUserSerializer)
		return SuccessResponse(data=data, msg="调用成功")

	# 更新用户信息
	def update(self, request):
		# 允许修改的字段
		allow = ['username', 'nick_name', 'mobile', 'email', 'role']

		data = allow_edit(allow, request)
		uid = request.data.get('id')
		if not uid:
			return ErrorResponse("请求参数错误!")

		user = SystemUser.objects.filter(id=uid, deleted=False)
		if not user:
			return ErrorResponse(msg="要修改的用户不存在或已删除")

		# 验证用户名是否已存在
		user_name = data.get('username')

		if user_name:
			tmp_user = SystemUser.objects.filter(username=user_name)
			if tmp_user and tmp_user.first().id == uid:
				data.pop('username')
			elif SystemUser.objects.filter(username=user_name).exists():
				return ErrorResponse(msg='用户名已存在')
		else:
			data.pop('username')

		# 验证手机号格式
		mobile = data.get('mobile')
		if mobile and not re.match(r'^1[356789]\d{9}$', mobile):
			return ErrorResponse(msg="输入的手机号格式不正确")

		# 验证邮箱格式
		email = data.get('email')
		if email and not re.match(r'^[0-9a-zA-Z_.-]+@[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*\.[0-9a-zA-Z-]{2,6}$', email):
			return ErrorResponse(msg="输入的邮箱地址不正确")

		if not data.get('role'):
			data.pop('role')

		user.update(**data)
		serializer = SystemUserSerializer(user, many=True)
		return SuccessResponse(code=ResponseCode.CREATE_SUCCESS, data=serializer.data, msg="修改成功")

	# 修改用户密码
	def change_password(self, request):
		uid = request.data.get('id')
		_password = request.data.get('original')
		raw_password = request.data.get('password')
		user = SystemUser.objects.filter(id=uid).filter(Q(status=True) & Q(deleted=False)).first()
		if user:
			if user.check_password(_password):
				if raw_password:
					user.set_password(raw_password)
				else:
					return ErrorResponse(msg="请输入要修改的密码")
				user.save()
			else:
				return ErrorResponse(msg="原密码不正确")
		else:
			return ErrorResponse(msg="原密码不正确")

		return SuccessResponse(msg="修改成功, 请使用新密码登录")

	# 找回密码
	def retrieve_password(self, request):
		uid = request.data.get('id')
		code = request.data.get('code')
		raw_password = request.data.get('password')
		user = SystemUser.objects.filter(id=uid).filter(Q(status=True) & Q(deleted=False)).first()
		if user:
			if code == "8888":
				if raw_password:
					user.set_password(raw_password)
					user.save()
					return SuccessResponse(msg="找回密码成功")
				else:
					return ErrorResponse(msg="密码不能为空")
			else:
				return ErrorResponse(msg="验证码错误")
		else:
			return ErrorResponse(msg="用户不存在")

	# 通过id获取用户信息
	def get_user_by_id(self, request):
		user_id = request.query_params.get('id')
		if not user_id:
			return ErrorResponse(msg='获取数据失败')
		user = SystemUser.objects.filter(deleted=False).filter(id=user_id)
		if not user:
			return ErrorResponse(msg='用户信息不存在')

		serializer = SystemUserSerializer(user, many=True)
		return SuccessResponse(serializer.data)

	# 删除用户
	def delete_user(self, request):
		id = request.query_params.get('id')

		if not id:
			return ErrorResponse(msg='请求参数错误')
		user = SystemUser.objects.filter(deleted=False).filter(id=id)
		if not user:
			return ErrorResponse(msg='用户已删除或不存在')
		user.update(deleted=True)

		return SuccessResponse(msg='删除成功!')

	# 搜索用户
	def search(self, request):
		query = request.query_params.get('query')
		if not query:
			return ErrorResponse(msg='请求参数错误')
		users = SystemUser.objects.filter(deleted=False).filter(
			Q(username__contains=query) | Q(nick_name__contains=query) | Q(mobile__contains=query))
		serializer = SystemUserSerializer(users, many=True)
		return SuccessResponse({'list': serializer.data}, msg='调用成功')

	# 修改用户状态
	def change_status(self, request):
		id = request.query_params.get('id')
		if not id:
			return ErrorResponse(msg='请求参数错误')
		user = SystemUser.objects.filter(deleted=False).filter(id=id)

		if not user:
			return ErrorResponse(msg='用户信息不存在')
		user_status = user.first().status
		user.update(status=not user_status)
		return SuccessResponse()
